<?php

namespace app\controllers;

use yii\web\Controller;
use vendor\animal\Cat;
use vendor\animal\Mourse;
use vendor\animal\Dog;
use \yii\base\Event;
use app\behaviors\Behavior1;

class AnimalController extends Controller
{
    public function actionIndex()
    {
        $cat = new Cat;
        $cat2 = new Cat;
        $mourse = new Mourse;
        $dog = new Dog;
        //事件绑定
        $cat->on('miao', [$mourse, 'run']);
        $cat->on('miao', [$dog, 'look']);
        //取消事件
        $cat->off('miao', [$dog, 'look']);
        //猫叫
        $cat->shout();
        $cat2->shout();//因为cat2没有进行事件绑定，所以他触发shout方法以后，不会有事件响应
    }

    public function actionIndex2()
    {
        $cat = new Cat;
        $cat2 = new Cat;
        $mourse = new Mourse;
        //类级别的事件绑定
        Event::on(Cat::className(), 'miao', [$mourse, 'run']);
        //不论是哪个实例，只要触发了事件，就会有响应。
        $cat->shout();
        $cat2->shout();
    }

    public function actionIndex3()
    {
        $cat = new Cat;
        $cat2 = new Cat;
        $mourse = new Mourse;
        //类级别的事件绑定  匿名函数
        Event::on(Cat::className(), 'miao', function () {
            echo 'miao event has triggered<br>';
        });
        //不论是哪个实例，只要触发了事件，就会有响应。
        $cat->shout();
        $cat2->shout();
    }

    public function actionIndex4()
    {
        \Yii::$app->on(\yii\base\Application::EVENT_AFTER_REQUEST, function () {
            echo "event after request";
        });
        echo "hello index4 action<br>";
    }

    /**
     * 行为
     *
     * @return null
     */
    public function actionIndex5()
    {
        $dog = new Dog();

        $dog->look();
        $dog->eat();
        $dog->height = '15cm';
        echo $dog->height;
    }

    /**
     * 行为事件
     *
     * @return null
     */
    public function actionIndex6()
    {
        $dog = new Dog();
        $dog->trigger('wang');
    }

    /**
     * 对象混合
     *
     * @return null
     */
    public function actionIndex7()
    {
        $dog = new Dog();
        $behavior1 = new Behavior1();
        //注入行为 此时可以在dog中删除掉响应的behaviors
        $dog->attachBehavior('beh1', $behavior1);
        //移除行为
        $dog->detachBehavior('beh1');
        $dog->eat();
    }


}